<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace app\controller\wechat;

use hiduoke\services\facade\WechatService;
use think\App;
use think\Exception;
use think\facade\Log;
use app\common\controller\WechatController;
use app\common\model\wechat\WechatOrder;

class Notify extends WechatController
{

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * @param int $plaid
     * @param string $addon
     */
    public function index($plaid = 0, $addon = '')
    {
        try {
            $response = WechatService::getOrderApp()->handlePaidNotify(function ($message, $fail) {

                if ($message['result_code'] === 'SUCCESS' && $message['return_code'] === 'SUCCESS') {
                    //查询是否支付成功
                    $order_query = WechatService::orderQuery($message['out_trade_no']);
                    if ($order_query['return_code'] === 'SUCCESS' && $order_query['result_code'] === 'SUCCESS') {
                        //数据库中搜索订单
                        $wechat_order = (new WechatOrder())->where(['out_trade_no' => $message['out_trade_no']])->find();
                        $order_id = $wechat_order->id;
                        if ($wechat_order) {
                            //更新支付状态
                            $update_data = array(
                                'transaction_id' => $message['transaction_id'],
                                'state'          => 1
                            );
                            $wechat_order->save($update_data);
                            $this->eventNotify($order_id, $message);
                        }
                    }
                }
                return true;
            });
        } catch (Exception $e) {
            Log::write("支付回调错误：".$e->getMessage());
        }
        $response->send();
    }

    /**
     * 触发支付通知事件
     * @param $order_id
     * @param $message
     */
    protected function eventNotify($order_id, $message)
    {
        $plaid = $this->request->param('plaid', 0);
        $addon = $this->request->param('addon', '');
        if ($addon) {
            event($addon . '_wechat_notify', [
                'plaid'   => $plaid,
                'addon'   => $addon,
                'order_id' => $order_id,
                'message' => $message,
            ]);
        }
    }
}
